package com.lhf.springcloud.controller;

import com.lhf.springcloud.Entity.StudentBasicData;
import com.lhf.springcloud.exception.StorageFileNotFoundException;
import com.lhf.springcloud.service.StudentEssentialInformationImpl;
import com.lhf.springcloud.utils.ExcelUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: FileUploadController
 * @Description:  实现文件上传
 * @Author: liuhefei
 * @Date: 2019/4/1
 * @blog: https://www.imooc.com/u/1323320/articles
 **/
@Controller
public class StudentEssentialInformation {
    @Autowired
    private StudentEssentialInformationImpl studentEssentialInformation;

    /**
     * 跳转到学生基本信息操作页面
     * @param model
     * @return
     * @throws IOException
     */
    @GetMapping("/studentEssentialInformation")
    @ApiOperation("展示学生基本信息")
    public String listUploadedFiles(Model model) throws IOException {
        return "project/dataCenter/studentEssentialInformation";
    }
    @RequestMapping(value = "/findAllStudentEssentialInformation",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("查询所有学生基本信息")
    public Map findAllData(){
        List<StudentBasicData> allData = studentEssentialInformation.findAllStudentEssentialInformation();
        Map map=new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",allData.size());
        map.put("data",allData);
        return map;
    }
    @RequestMapping(value = "/findByStudentEssentialInformationIdCard",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("通过学生身份证号查询学生基本信息")
    @ApiImplicitParam(name = "idCard",value = "身份证号")
    public Map findByIdCard(String idCard){
        List<StudentBasicData> allData = studentEssentialInformation.findByIdCard(idCard);
        Map map=new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",allData.size());
        map.put("data",allData);
        return map;
    }
    @ApiOperation("通过id更改学生基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "value",value = "更新后的新值"),
            @ApiImplicitParam(name = "id",value = "字段id"),
            @ApiImplicitParam(name = "field",value = "需要更新的字段名")
    })
    @RequestMapping(value = "/updateStudentEssentialInformation",method = RequestMethod.GET)
    public String updateData(String value,String id,String field){
        studentEssentialInformation.updateData(value,id,field);

        return "redirect:/studentEssentialInformation";
    }
    @GetMapping("/studentEssentialInformationFiles")
    @ResponseBody
    @ApiOperation("文件下载")
    public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        // 下载本地文件
        String fileName = "学生基本信息表.xlsx".toString(); // 文件的默认保存名
        // 读到流中
        String property = System.getProperty("user.dir");
//        InputStream inStream = new FileInputStream("http://192.168.7.22:888/project/excel/学生基础数据表.xlsx");// 文件的存放路径
        InputStream inStream = new FileInputStream(property+"/excel/学生基本信息表.xlsx");// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        try {
            response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //文件上传
    @PostMapping("/upLoadStudentEssentialInformation")
    @ApiOperation("文件上传")
    @ApiImplicitParam(name = "file",value = "需要上传的文件")
    public String handleFileUpload(@RequestParam("file")MultipartFile file, RedirectAttributes redirectAttributes){
        if(file.isEmpty()) {
            return "redirect:/studentEssentialInformation";
        }
        List<StudentBasicData> list1= new ArrayList<>();
        String s =null;
        try {
            InputStream inputStream = file.getInputStream();
            List<List<Object>> list = ExcelUtils.getCourseListByExcel(inputStream, file.getOriginalFilename());
            inputStream.close();

            for (int i = 1; i < list.size(); i++) {
                List<Object> courseList = list.get(i);

                StudentBasicData course = new StudentBasicData();
                if (courseList.size()==0){
                    break;
                }
                course.setStudentName(courseList.get(0).toString());
                course.setStudentXJ(courseList.get(1).toString());
                course.setEntrance(courseList.get(2).toString());

                course.setStudentStatus(courseList.get(3).toString());
                course.setPolitical(courseList.get(4).toString());
//                if (Double.valueOf(String.valueOf(courseList.get(5)))>100||Double.valueOf(String.valueOf(courseList.get(5)))<0){
//                    redirectAttributes.addFlashAttribute("message", "第"+i+"行学生成绩异常，请核对后上传!" );
//                    list1.clear();
//                    break;
//                }
                course.setFamilyPhotoNumber(courseList.get(5).toString());
                course.setStudentAddress(courseList.get(6).toString());
                course.setIdCard(courseList.get(7).toString());
                course.setPhotoNumber(courseList.get(8).toString());
                course.setStudentImgUrl(courseList.get(9).toString());
                list1.add(course);
                // 执行插入操作

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list1.size()>0){
          s = studentEssentialInformation.addCourse(list1);
        }
        redirectAttributes.addFlashAttribute("messages", s);

        return "redirect:/studentEssentialInformation";  //重定向
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }


}
